﻿using System;
using System.Linq;
using DBCore.Attr;
using System.Threading.Tasks;

namespace DBCore.DB
{
    /// <summary>
    /// 
    /// </summary>
    public class DAOFactory
    {
        public static IDAO CreateDao(Type typ)
        {
            var attributes = typ.GetCustomAttributes(typeof(EntityAttribute), true);
            var attr = (EntityAttribute)attributes[0];
            
            var types = IOC.GetSubTypes(typeof(IDAO).FullName);
            if (types.Count == 0)
            {
                return null;
            }
            else
            {
                var type = (from t in types where Database.DBS.ContainsKey(attr.Database) && IOC.Types[t].ThisType.Name.Split('`')[0].ToLower() == Database.DBS[attr.Database].DbType.ToLower() + "dao" select IOC.Types[t].ThisType).FirstOrDefault();
                if (type == null)
                {
                    return null;
                }
                else
                {
                    var handle = Activator.CreateInstance(type);
                    IDAO obj = handle as IDAO;
                    if (null == obj)
                    {
                        Func<string, IDAO> GetIDao = x => {
                            return (IDAO)System.Reflection.Assembly.Load("DBCore").CreateInstance(x, false);
                        };

                        obj =GetIDao(type.FullName);  
                    }
                    return obj;
                }
            }
        }
    }
}
